<?php
/**
 * 后台栏目模型继承上层栏目模型
 * AdminCategory.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author huangdaohai <huangdaohai.2007@163.com>
 * @version V1.0
 * @access public
 */
class AdminCategory extends CategoryModel
{
	/**
	 * AdminCategory::getCategoryData()
	 * 
	 * @return
	 */
	public static function getCategoryData($params = array()){
	    $sWhere = '1';
	    if( is_array($params) && $params){
	       foreach( $params as $sKey=>$sVal ){
	           $sWhere.= ' AND t.'.$sKey.'='.$sVal;
	       }
	    }
		$model=self::model()->with(array('modelinfo'=>array('select'=>'model_name')))->findAll(
                    array(
                        'select'=> 't.cate_id ,t.sort ,t.parent_id ,t.isnave ,t.sort ,t.url ,t.cate_name ,t.cate_name ,t.items ,t.cate_type',
                        'condition'=> $sWhere ,
                        'order' => 't.`sort` asc'
                    )
                );
		$arr = array();
		foreach ($model as $v){
		  //print_r($v->modelinfo->model_name);exit;
			$str_manage = array();
			$str_manage[]=CHtml::link('添加下级分类',Yii::app()->createUrl('/admin/category/add' ,array('pid'=>$v->cate_id)));
			if(Yii::app()->user->checkAccess('category|update')){
				$str_manage[]=CHtml::link('编辑',Yii::app()->createUrl('/admin/category/edit',array('pid'=>$v->parent_id ,'cate_id'=>$v->cate_id)));
			}
			if(Yii::app()->user->checkAccess('category|delete')){
				$str_manage[]=CHtml::link('删除','javascript:void(0);' ,array('url'=>Yii::app()->createUrl('/admin/category/delete',array('cate_id'=>$v->cate_id)) ,'class'=>'delete'));
			}
            $linkurl = $v->url ? CHtml::link('访问' ,$v->url ,array('target'=>'_blank')) : CHtml::link('访问' ,'javascript:void(0);');
			$arr[]=array(
                    'id' =>$v->cate_id,
                    'parentid'=>$v->parent_id,
					'sort'=>$v->sort,
                    'isnave' =>  $v->isnave==2 ? '<b class="red">否</b>' : '',
                    'url' => Yii::app()->createUrl('/admin/category/ajaxSort' ,array('cate_id'=>$v->cate_id)),
                    //'spacer' => '&nbsp|-',
                    'cate_name' =>$v->cate_name,
                    'cate_type' => Yii::app()->dict->get('category' ,'catetype' ,$v->cate_type),
                    'model_name' => isset($v->modelinfo->model_name) ? $v->modelinfo->model_name : '',
                    'items' => $v->items,
                    'linkurl' => $linkurl,
					'str_manage'=>!empty($str_manage)?join(' ', $str_manage):''
			);
		}
		return $arr;
	}
    /**
     * AdminCategory::saveData() 保存数据
     * 
     * @param array $attributes 属性数组
     * @param bool $isverify 是否验证
     * @return mix 保存成功返回 主键ID  失败返回错误数组
     */
    public function saveData($attributes ,$isverify=true){
        $this->attributes=$attributes;
        if( $isverify ){
            if( $this->save() ){
                //保存成功             
                return $this->cate_id;
            } else {
                return $this->errors;
            }
        } else {
            $this->save(false);
            return $this->cate_id;
        }        
    }
    public function getOne($key){
        $oData = $this->findByPk($key);
        return $oData->attributes;
    }
    /**
     * AdminCategory::updateCounters() 更新内容数量
     * 
     * @param mixed $number 1 为加 -1 减
     * @param mixed $catid 栏目ID
     * @return void
     */
    public static function updateCounts($number ,$catid){
        if(self::model()->updateCounters(array('items'=>1), 'cate_id='.$catid)){
            return true;
        }
        return false;
        
    }
    
    /**
     * CmsModel::deleteData()
     * 
     * @param mixed $oModel
     * @return
     */
    public function deleteData($iCateId){
        $bReslut = true;
        //删除对应模型字段
        
        if( !self::model()->deleteAll('FIND_IN_SET("'.$iCateId.'" ,parent_ids)') ) $bReslut = false;
        //$oDmodel = self::model()->findByPk($iCateId);
        
        //if( !$oDmodel->delete() ) $bReslut = false;
        return $bReslut;
    }
    /**
     * BaseCategoryModel::getCategoryJson() 获取栏目层极JSON
     * 
     * @param string $fid
     * @return json
     */
    public static function getCategoryJson($fid=''){
		$where = 'where 1 ';
		if(!empty($fid)){
			$where.=' cate_type!=3 and parent_id="'.$fid.'"';
		}
		$sql = 'select * from {{category}} '.$where.' order by sort asc ,cate_id asc';
		$menuAll = Yii::app()->db->createCommand($sql)->queryAll();
		$menu=array();
		$result=array();
		foreach ($menuAll as $v){
			$result[$v['cate_id']]=$v;
		}
		foreach ($result as $k=>$v){
			$fid=$v['parent_id'];
			if($fid==0){
				$menu[]=&$result[$k];
			}else{
				$result[$fid]['child'][$k]=&$result[$k];//引用当前循环的这一个值，为其找到父级
			}
		}
		$return_menu = AdminCategory::getChildCategory($menu,$fid);
		$jGoodsClass = json_encode($return_menu);
		return $jGoodsClass;
	}
	/**
	 * BaseCategoryModel::getChildCategory()
	 * 
	 * @param mixed $menu
	 * @param mixed $cur_menu
	 * @return
	 */
	public static function getChildCategory($menu,$cur_menu){
		if(empty($menu)) return false;
		$aReturn='';
		foreach ($menu as $v){
			if(isset($v['child']) && !empty($v['child'])){
				$aReturn[]=array(
								'text'=>$v['cate_name'],
								'id'=>$v['cate_id'],
								//'checked'=>in_array($v['menu_id'], $cur_menu)?true:false,
								//'checked'=>false,
								'expanded'=>true,
								'children'=> AdminCategory::getChildCategory($v['child'],$cur_menu)
						   );
			}else{
			    if( $v['cate_type']==1 ){
			        $sUrl = Yii::app()->createUrl('/admin/content/index' ,array('cate_id'=>$v['cate_id']));       
			    } elseif( $v['cate_type']==2 ) {
			         $sUrl = Yii::app()->createUrl('/admin/content/addpage' ,array('cate_id'=>$v['cate_id'])); 
			    }			    
				$aReturn[]=array(
								'text'=>"<a href='$sUrl' target='content-right'>".$v['cate_name']."</a>",
								'id'=>$v['cate_id'],
								//'checked'=>in_array($v['menu_id'], $cur_menu)?true:false,
								'expanded'=>true
						   );
			}
		}
		return $aReturn;
	}
}